//
//  DBJLeftBarController.m
//  DBJ
//
//  Created by 花化华 on 2016/11/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "DBJLeftBarController.h"
#import "WDWavesView.h"
#import <Masonry.h>
#import "DBJTabBarController.h"
#import "DBJDBJLeftBarCell.h"
#import "DBJUserAccountModel.h"
#import "DBJLoginViewController.h"
#import "DBJRegistViewController.h"
#import "DBJPersonInfoTableViewController.h"

/** CellID */
static NSString *CELLID = @"LEFTBARCELL_ID";

@interface DBJLeftBarController () <UITableViewDelegate,UITableViewDataSource>

/** tableView */
@property (nonatomic,strong)UITableView *tableView;
/** Cell数据模型 */
@property (nonatomic,strong)NSArray *models;
/** Cell对应跳转的VC */
@property (nonatomic,strong)NSArray *cellVCs;

/** tableView头视图 */
@property (strong, nonatomic) WDWavesView *wavesView;
/** tableView头视图的icon */
@property (nonatomic, strong) UIView *headerView;

/** 个人信息相关 */
@property (nonatomic,strong) UIButton *iconButton;
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *infoLabel;

@property (nonatomic, strong) ICSDrawerController *ISCDController;

@end

@implementation DBJLeftBarController

- (void)dbjSetupNavigationItems{
    [super dbjSetupNavigationItems];
}

- (void)dbjSetupSubviews{
    [super dbjSetupSubviews];
    
    //设置背景色
    self.view.backgroundColor = DBJColor;
    
    //创建WDWavesView
    _wavesView = [[WDWavesView alloc]init];
    _wavesView.backgroundColor = DBJColor;
    [self.view addSubview:_wavesView];
    _wavesView.frame = CGRectMake(0, 64, self.view.w, 110);
    [_wavesView addSubview:self.headerView];
    
    __weak typeof(self)weakSelf = self;
    _wavesView.waveBlock = ^(CGFloat currentY){
        
        //修改头view的高度
        CGRect iconFrame = weakSelf.headerView.frame;
        
        iconFrame.origin.y = CGRectGetHeight(weakSelf.wavesView.frame)-CGRectGetHeight(weakSelf.headerView.frame)+currentY-weakSelf.wavesView.waveHeight;
        
        weakSelf.headerView.frame  =iconFrame;
    };
    [_wavesView startWaveAnimation];
    
    //如果登录了则加载相关入口
    if ([DBJUserAccountModel sharedUserAccount].currentID) {
        [self loadData];
        
        //创建tableView
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = DBJColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[DBJDBJLeftBarCell class] forCellReuseIdentifier:CELLID];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_wavesView.mas_bottom);
            make.left.right.bottom.equalTo(self.view);
        }];
    }
    
    //注册通知
    //--登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeRootViewController:) name:LOGINSUCCESS object:nil];
    //--更新leftBar的个人信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInfo) name:@"UPDATELEFTINFO" object:nil];
}

#pragma mark - 更新leftBar的个人信息
- (void)updateInfo{
 
    //设置中间头像
    //获取本地存储的头像
    UIImage *image;
    NSString *name = [DBJUserDefaultsTool objetForKey:CURRENTID];
    NSData *iconData = [DBJUserDefaultsTool objetForKey:[NSString stringWithFormat:@"%@-ICON",name]];
    UIImage *iconImage = [UIImage imageWithData:iconData];
    
    if (iconImage) {
        image = iconImage;
    }else{
        image = [UIImage imageNamed:@"doctor_defaultphoto_male"];
    }
    
    [_iconButton setImage:image forState:UIControlStateNormal];
    
    //获取当前用户对应的model
    DBJLoginModel *model = [DBJTools getCurrentIDModel];
    _nameLabel.text = model.true_name;
    _infoLabel.text = model.mobile_number;
    
}

#pragma mark - 登录后需要加载的页面数据
- (void)loadData{
    _models = @[@"名医申请",@"病例管理",@"关注医生",@"设置与帮助",@"注销"];
    
    _cellVCs = @[@"DBJDoctorApplyTableViewController",@"DBJIllnessCaseManageViewController"
                 ,@"DBJAttentionDoctorTableViewController",@"DBJSettingAndHelpTableViewController"];
}

#pragma mark - 懒加载
/**
 * 创建头视图
 */
- (UIView *)headerView{
    if (!_headerView) {
        //创建headerView
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 216, 66)];
            
        //创建iconButton
        UIButton *iconButton= [[UIButton alloc] init];
        _iconButton = iconButton;
        
        //设置中间头像
        //获取本地存储的头像
        UIImage *image;
        NSString *name = [DBJUserDefaultsTool objetForKey:CURRENTID];
        NSData *iconData = [DBJUserDefaultsTool objetForKey:[NSString stringWithFormat:@"%@-ICON",name]];
        UIImage *iconImage = [UIImage imageWithData:iconData];
        
        if (iconImage) {
            image = iconImage;
        }else{
            image = [UIImage imageNamed:@"doctor_defaultphoto_male"];
        }
        
        [iconButton setImage:image forState:UIControlStateNormal];
        iconButton.layer.borderColor = [UIColor whiteColor].CGColor;
        iconButton.layer.borderWidth = 2;
        iconButton.layer.cornerRadius = 25;
        //控制是否可点击
        iconButton.userInteractionEnabled = NO;
        //将多余的部分截取
        iconButton.clipsToBounds  = YES;
        [_headerView addSubview:iconButton];
        
        //设置登录后的leftBar的头视图布局
        if ([DBJUserAccountModel sharedUserAccount].currentID) {
        
            //设置iconButton的frame
            iconButton.frame = CGRectMake(17, 0, 50, 50);
            
            //获取当前用户对应的model
            DBJLoginModel *model = [DBJTools getCurrentIDModel];
//            NSLog(@"%@",model);
            
            UILabel *nameLabel = [UILabel hm_labelWithText:model.true_name fontSize:15 color:[UIColor whiteColor]];
            _nameLabel = nameLabel;
            nameLabel.frame = CGRectMake(75, 0, 130, 25);
            [_headerView addSubview:nameLabel];
            
            //创建infoLabel
            UILabel *infoLabel = [UILabel hm_labelWithText:model.mobile_number fontSize:15 color:[UIColor whiteColor]];
            _infoLabel = infoLabel;
            infoLabel.frame = CGRectMake(75, 30, 130, 25);
            [_headerView addSubview:infoLabel];
            
            //headerView添加点击手势
            UITapGestureRecognizer *tapGestureRecongnizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerViewGestureRecongnizer)];
            [_headerView addGestureRecognizer:tapGestureRecongnizer];
            
        }else{//设置没有登录时的leftBar的头视图布局
            
            //创建注册按钮
            UIButton *registerButton = [[UIButton alloc]initWithFrame:CGRectMake(17, 25, 50, 25)];
            registerButton.titleLabel.font = [UIFont systemFontOfSize:15];
            [registerButton setTitle:@"注 册" forState:UIControlStateNormal];
            
            [registerButton addTarget:self action:@selector(registerClick:) forControlEvents:UIControlEventTouchUpInside];
            [_headerView addSubview:registerButton];
            
            //设置iconButton的frame
            iconButton.frame = CGRectMake(84, 0, 50, 50);
            
            //创建登录按钮
            UIButton *loginButton = [[UIButton alloc]initWithFrame:CGRectMake(151, 25, 50, 25)];
            loginButton.titleLabel.font = [UIFont systemFontOfSize:15];
            [loginButton setTitle:@"登 录" forState:UIControlStateNormal];
            [loginButton addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
            [_headerView addSubview:loginButton];
            
        }

    }
    return _headerView;
}

/** 
 * 头像按钮点击事件 
 */
- (void)headerViewGestureRecongnizer{
    DBJPersonInfoTableViewController *personInfoViewController = [[DBJPersonInfoTableViewController alloc]init];
    [self skipViewController:personInfoViewController andTitle:@"个人信息"];
}

/**
 * 注册按钮点击事件
 */
- (void)registerClick:(UIButton *)sender{
    DBJRegistViewController *registViewController = [[DBJRegistViewController alloc]init];
    [self skipViewController:registViewController andTitle:@"注册"];
}

/**
 * 登录按钮点击事件
 */
- (void)loginClick:(UIButton *)sender{
    DBJLoginViewController *loginViewController = [[DBJLoginViewController alloc]init];
    [self skipViewController:loginViewController andTitle:@"登录"];
}

/**
 * 重新加载控制器
 */
- (ICSDrawerController *)ISCDController{
    if (!_ISCDController) {
        
        _ISCDController = [[ICSDrawerController alloc]initWithLeftViewController:[[DBJLeftBarController alloc]init] centerViewController:[[DBJTabBarController alloc]init]];
    }
    
    return _ISCDController;
}

#pragma mark - loginViewController通知响应
/**
 *  更改根控制器
 *
 *  @param some NSNotification
 */
- (void)changeRootViewController:(NSNotification *)some{

    if ([DBJUserAccountModel sharedUserAccount].currentID)
        [DBJTools dbjShowSVSuccessTitle:@"登录成功" andTime:STANTIME];
    
    CATransition *animation = [[CATransition alloc] init];
    animation.duration = 1.0;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionFade;
    
    [UIApplication sharedApplication].keyWindow.rootViewController = self.ISCDController;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:animation forKey:@"animation"];
        
}

#pragma mark - tableView数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //1.获取模型
    NSString *model = _models[indexPath.row];
    
    //2.创建cell
    DBJDBJLeftBarCell *cell = [tableView dequeueReusableCellWithIdentifier:CELLID forIndexPath:indexPath];
    
    //3.为cell设置数据
    cell.model = model;

    //4.返回cell
    return cell;
}

#pragma mark - tableView的代理方法
/** 设置分组style的头间隔 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row < _cellVCs.count) {
        
        //1.获取当前行数据模型
        NSString *cellVC = _cellVCs[indexPath.row];
        //2.获取需要跳转的控制器的class
        Class vcClass = NSClassFromString(cellVC);
        //3.创建控制器
        UIViewController *controller = [[vcClass alloc]init];
        //4.跳转
        [self skipViewController:controller andTitle:_models[indexPath.row]];
        
    }else if(indexPath.row == _models.count-1){//注销
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您确定要注销？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"注销" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [DBJTools dbjShowSVSuccessTitle:@"注销成功" andTime:STANTIME];
            
            [DBJUserDefaultsTool removeObjectForKey:CURRENTID];
            //发送通知登录、DBJLeftBarController接收
            [[NSNotificationCenter defaultCenter] postNotificationName:LOGINSUCCESS object:nil userInfo:nil];
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
}

#pragma mark - leftBar控制器跳转
- (void)skipViewController:(UIViewController *)viewController andTitle:(NSString *)title{
    //设置title
    viewController.title = title;
    //通过drawer获取导航条
    UITabBarController *tab = (UITabBarController *)self.drawer.centerViewController;
    UINavigationController *nav = tab.selectedViewController;
    [nav popToRootViewControllerAnimated:NO];
    //关闭抽屉效果
    [self.drawer close];
    [nav pushViewController:viewController animated:NO];
}

@end
